import qs from '../components/qs'
import {
	domain
} from '@/common/index.js'

export const getDomain = function() {
	return domain;
}

export const errHandler = function(res) {
	if (res.statusCode == 401) {
		uni.redirectTo({
			url: '/pages/login/login',
			success: (res) => {
			
			},
			fail: (err) => {

			}
		})
		return false
	} else if (res.statusCode != 200 && res.statusCode != 201) {
		// uni.hideLoading();
		// uni.showToast({
		// 	title: res.message ? res.message : res.data.message,
		// 	icon: 'none',
		// 	duration: 1500
		// })
		return false
	}
	return true
}

export const request = (method, url, body, queryParameters) => {
	method = method.toUpperCase();
	let keys = Object.keys(queryParameters)
	let queryUrl = url
	if (keys.length > 0) {
		queryUrl = queryUrl + '?' + qs.stringify(queryParameters)
	}
	let token = uni.getStorageSync('token');
	if (body || method == 'POST' || method == 'PUSH') {
		let header = {
			"content-type": "application/json",
			"Authorization": token
		};
		token != '' ? header.Authorization = token : '';
			return new Promise((resolve, reject) => {
				uni.request({
					url: queryUrl,
					method: method,
					data: body,
					header: header,
					timeout: 90000,
					success: function(res) {
						let Handler = errHandler(res);
						if (!Handler) {
							return reject(res.data);
						} else {
							resolve(res.data);
						}
					},
					fail: (err) => {
						reject(err);
					}
				})
			})

	} else if (method === 'GET' || method === 'DELETE') {
		let header = {
			"content-type": "application/x-www-form-urlencoded",
			"Authorization": token
		};
		token != '' ? header.Authorization = token : '';
			return new Promise((resolve, reject) => {
				uni.request({
					url: queryUrl,
					method: method,
					header: header,
					timeout: 90000,
					success: (res) => {
						let Handler = errHandler(res);
						if (!Handler) {
							return reject('失败');
						} else {
							resolve(res.data);
						}
					},
					fail: (err) => {
						reject(err);
					}
				})
			})
	}
}
